// const createError = require("http-errors");
const joi = require("joi");
const path = require("path");
const express = require("express");
const logger = require("morgan");
const cors = require("cors");
const expressJWT = require("express-jwt");
const { jwtConfig, filePath } = require("./config/application.config");

const app = express();

const loginRouter = require("./routes/login");
const userRouter = require("./routes/user");
const fileRouter = require("./routes/file");
const menuRouter = require("./routes/menu");
const areaRouter = require("./routes/area");
const demoRouter = require("./routes/demo");

// 全局中间件 挂载提示函数
app.use((req, res, next) => {
  // -1 失败 0 成功 401 身份验证失败
  res.tip = (err, code = -1) => {
    res.send({
      code,
      message: err instanceof Error ? err.message : err,
    });
  };
  next();
});

app.use(cors());
app.disable("etag");
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use("/file_assets", express.static(filePath));
app.use(
  expressJWT({ secret: jwtConfig.jwtSecretKey }).unless({
    path: [/^\/api\//, /^\/file_assets\//, /^\/demo\//],
  })
);

// 捕获404错误
// app.use((req,res,next)=>{
//   next(createError(404))
// })

app.use("/api", loginRouter);
app.use("/user", userRouter);
app.use("/file", fileRouter);
app.use("/menu", menuRouter);
app.use("/area", areaRouter);
app.use("/demo", demoRouter);

app.use(function (err, req, res, next) {
  if (err.name === "UnauthorizedError") return res.tip("身份认证失败！", 401);
  // 数据验证失败
  if (err instanceof joi.ValidationError) return res.tip(err);
  // 未知错误
  res.tip(err);
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
